# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime

from django.shortcuts import render, redirect, reverse
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from django.contrib.auth.decorators import login_required
from django.contrib.auth.hashers import make_password
from django.http import JsonResponse

from .models import UserProfile, Customer
from operation.models import HotelOrder
from room.models import Room, RoomStatus, RoomType


class CustomBackend(ModelBackend):
    def authenticate(self, username=None, password=None, **kwargs):
        try:
            user = UserProfile.objects.get(Q(username=username) | Q(email=username))
            if user.check_password(password) and user.type < 4:
                return user
        except Exception as e:
            return None

def user_login(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return redirect(reverse('index'))
    return render(request, 'login.html')

def user_logout(request):
    logout(request)
    return redirect(reverse('login'))

def index(request):
    res = {}
    hotel_order = HotelOrder.objects.filter(type__in=[1,2], 
        e_time__gte=datetime.date.today()).order_by('room_num')
    order_list = []
    for i in hotel_order:
        item = {}
        item['room_num'] = i.room_num
        item['people_num'] = i.people_num
        item['s_time'] = i.s_time
        item['e_time'] = i.e_time
        r = Room.objects.get(num=i.room_num)
        item['room_status'] = RoomStatus.get(r.status)
        item['room_type'] = RoomType.objects.get(type_num=i.room_type).name
        item['username'] = i.name
        order_list.append(item)
    res['order_list'] = order_list
    return render(request, 'index.html', res)

def about(request):
    res = {}
    res['active'] = 'about'
    res['display'] = 5
    return render(request, 'about.html', res)

def staff_info(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        email = request.POST.get('email')
        password = request.POST.get('password')
        mobile = request.POST.get('mobile')
        age = request.POST.get('age')
        gender = request.POST.get('gender')
        id_card = request.POST.get('id_card')
        type = request.POST.get('type')
        user = UserProfile.objects.create(
            username=username, 
            email=email,
            password=make_password(password),
            mobile=mobile,
            age=age,
            gender=gender,
            type=int(type),
            id_card=id_card,
            )
        user.save()
    res = {}
    staff_list = UserProfile.objects.filter(~Q(type=5))
    res['staff_list'] = staff_list
    res['active'] = 'staff'
    res['display'] = 4
    return render(request, 'staff.html', res)

def add_staff(request):
    username = request.POST.get('username')
    email = request.POST.get('email')
    password = request.POST.get('password')
    mobile = request.POST.get('mobile')
    age = request.POST.get('age')
    gender = request.POST.get('gender')
    id_card = request.POST.get('id_card')
    staff_type = request.POST.get('staff_type')
    user = UserProfile.objects.create(
        username=username, 
        email=email,
        password=make_password(password),
        mobile=mobile,
        age=age,
        gender=gender,
        type=int(staff_type),
        id_card=id_card,
        )
    user.save()
    res = {}
    res['status'] = 'ok'
    res['data'] = user.id
    return JsonResponse(res)

def staff_edit(request):
    msg = ''
    if request.method == 'POST':
        username = request.POST.get('username')
        email = request.POST.get('email')
        id_card = request.POST.get('id_card')
        mobile = request.POST.get('mobile')
        age = request.POST.get('age')
        gender = request.POST.get('gender')
        id = request.POST.get('id')
        type = request.POST.get('type')
        user = UserProfile.objects.get(id=id)
        user.username=username
        user.email=email
        user.id_card=id_card
        user.mobile=mobile
        user.age=age
        user.gender=gender
        user.type=type
        user.save()
        msg = '修改成功！'
    res = {}
    id = request.GET.get('id')
    staff = UserProfile.objects.get(id=int(id))
    res['staff'] = staff
    res['active'] = 'staff'
    res['display'] = 4
    res['msg'] = msg
    return render(request, 'staff_edit.html', res)

def staff_delete(request):
    id = request.GET.get('id')
    UserProfile.objects.filter(id=id).delete()
    return redirect('/staff')


def client_info(request):
    res = {}
    id = request.GET.get('id')
    page = int(request.GET.get('page', 0))
    if id:
        Customer.objects.filter(id=id).delete()
    user_name = request.POST.get('name')
    client_list = []
    if user_name:
        r = Customer.objects.filter(name=user_name)
    else:
        r = Customer.objects.all()[page*20:page*20+20]
    for i in r:
        item = {}
        item['id'] = i.id
        item['name'] = i.name
        item['mobile'] = i.mobile
        item['id_card'] = i.id_card
        item['gender'] = i.get_gender_display
        item['rant'] = i.rant
        r1 = HotelOrder.objects.filter(id_card=i.id_card)
        money = 0
        for j in r1:
            money += float(j.money)
        item['money'] = money
        client_list.append(item)
    res['client_list'] = client_list
    res['active'] = 'client'
    res['display'] = 4
    res['page_pre'] = page-1 if page>0 else 0
    res['page_next'] = page+1
    return render(request, 'client.html', res)

def client_edit(request):
    res = {}
    if request.method == 'POST':
        id = request.POST.get('id')
        mobile = request.POST.get('mobile')
        rant = request.POST.get('rant')
        Customer.objects.filter(id=id).update(mobile=mobile,rant=rant)
        return redirect('/client')
    id = request.GET.get('id')
    info = Customer.objects.get(id=id)
    res['active'] = 'client'
    res['display'] = 4
    res['client'] = info
    return render(request, 'client_edit.html', res)

def change_pwd(request):
    msg = ''
    s_msg = ''
    if request.method == 'POST':
        old_pwd = request.POST.get('old_pwd')
        new_pwd = request.POST.get('new_pwd')
        new_pwd1 = request.POST.get('new_pwd1')
        user = request.user
        if new_pwd == new_pwd1:
            user.password = make_password(new_pwd)
            user.save()
            s_msg = '修改成功！'
            login(request, user)
        else:
            msg = '修改失败！'
    res = {}
    res['msg'] = msg
    res['s_msg'] = s_msg
    res['active'] = 'change_pwd'
    res['display'] = 5
    return render(request, 'change_pwd.html', res)
